package com.one.group.admin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.one.group.enums.ErrorCode;
import com.one.group.model.dto.*;
import com.one.group.model.entity.Owner;
import com.one.group.model.vo.OwnerListVo;
import com.one.group.model.vo.OwnerDetailVo;
import com.one.group.result.Result;
import com.one.group.service.OwnerService;
import com.one.group.utils.ResultUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import com.alibaba.excel.EasyExcel;
import com.one.group.admin.excel.OwnerData;

@RestController
@RequestMapping("/owner")
@Tag(name = "业主管理接口")
public class OwnerController {

    @Autowired
    private OwnerService ownerService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @Operation(summary = "添加业主")
    public Result add(@Valid @RequestBody OwnerAddDto ownerAddDto, BindingResult bindingResult) {
        //1.校验
        if(bindingResult.hasErrors()){
            List<ObjectError> errors = bindingResult.getAllErrors();
            StringBuilder sb = new StringBuilder();
            errors.forEach(objectError -> {
                String message = objectError.getDefaultMessage();
                sb.append(message).append(",");
            });
            return ResultUtil.error(ErrorCode.ADD_ERROR.getCode(),sb.toString());
        }
        boolean result = ownerService.addOwner(ownerAddDto);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.ADD_ERROR.getCode(), "添加业主失败");
        }
    }
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @Operation(summary = "业主列表")
    public Result<PageInfo<OwnerListVo>> list(OwnerQueryDto ownerQueryDto){

        //1.分页条件
        PageHelper.startPage(ownerQueryDto.getPage(),ownerQueryDto.getLimit());

        List<OwnerListVo> list = ownerService.getOwnerList(ownerQueryDto);

        //3.分页结果
        PageInfo<OwnerListVo> pageInfo = new PageInfo<>(list);
        return ResultUtil.success(pageInfo);
    }
    @RequestMapping(value = "/moveOut",method = RequestMethod.POST)
    @Operation(summary = "业主迁出")
    public Result moveOut(@RequestBody Long houseId){
        boolean result = ownerService.moveOutOwner(houseId);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "业主迁出失败");
        }
    }
    //批量迁出
    @RequestMapping(value = "/moveOutBatch",method = RequestMethod.POST)
    @Operation(summary = "批量业主迁出")
    public Result moveOutBatch(@RequestBody List<Long> houseIds){
        boolean result = ownerService.moveOutOwnerBatch(houseIds);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "批量业主迁出失败");
        }
    }

    @RequestMapping(value = "/moveIn",method = RequestMethod.POST)
    @Operation(summary = "业主迁入")
    public Result moveIn(@RequestBody OwnerMoveInDto moveInDto){
        if (moveInDto.getOwnerId() == null || moveInDto.getHouseId() == null || moveInDto.getMoveInTime() == null) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), "参数不能为空");
        }
        
        boolean result = ownerService.moveInOwner(moveInDto.getOwnerId(), moveInDto.getHouseId(), moveInDto.getMoveInTime());
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "业主迁入失败");
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Operation(summary = "修改业主信息")
    public Result update(@Valid @RequestBody OwnerUpdateDto ownerUpdateDto, BindingResult bindingResult) {
        //1.校验
        if(bindingResult.hasErrors()){
            List<ObjectError> errors = bindingResult.getAllErrors();
            StringBuilder sb = new StringBuilder();
            errors.forEach(objectError -> {
                String message = objectError.getDefaultMessage();
                sb.append(message).append(",");
            });
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), sb.toString());
        }
        
        //2.构建Owner实体
        Owner owner = new Owner();
        owner.setId(ownerUpdateDto.getId());
        owner.setCellId(ownerUpdateDto.getCellId());
        owner.setName(ownerUpdateDto.getName());
        owner.setPhone(ownerUpdateDto.getPhone());
        owner.setGender(ownerUpdateDto.getGender());
        owner.setEmail(ownerUpdateDto.getEmail());
        owner.setRemark(ownerUpdateDto.getRemark());
        owner.setIdCard(ownerUpdateDto.getIdCard());
        owner.setMoveInTime(ownerUpdateDto.getMoveInTime());
        owner.setResidentType(ownerUpdateDto.getResidentType());
        
        //3.调用service进行修改
        boolean result = ownerService.updateById(owner);
        
        //4.封装返回结果
        if(result){
            return ResultUtil.success();
        }
        return ResultUtil.error(ErrorCode.UPDATE_ERROR.getCode(), "修改业主失败");
    }

    @RequestMapping(value = "/approvedBatch",method = RequestMethod.POST)
    @Operation(summary = "批量通过审核")
    public Result approvedBatch(@RequestBody List<Long> ownerIds){
        boolean result = ownerService.auditOwnerBatch(ownerIds, 1);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "通过审核失败！");
        }
    }

    @RequestMapping(value = "/disapprovedBatch",method = RequestMethod.POST)
    @Operation(summary = "批量不通过审核")
    public Result disapprovedBatch(@RequestBody List<Long> ownerIds){
        boolean result = ownerService.auditOwnerBatch(ownerIds, 3);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "不通过审核失败！");
        }
    }

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @Operation(summary = "获取业主详情")
    public Result<OwnerDetailVo> getDetail(@RequestParam Long ownerId) {
        if (ownerId == null) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), "业主ID不能为空");
        }
        
        OwnerDetailVo ownerDetail = ownerService.getOwnerDetailById(ownerId);
        if (ownerDetail == null) {
            return ResultUtil.error(ErrorCode.NOT_FOUND_ERROR.getCode(), "业主不存在");
        }
        
        return ResultUtil.success(ownerDetail);
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @Operation(summary = "批量导入业主信息")
    public Result<String> importOwners(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), "请选择要导入的Excel文件");
        }
        
        try {
            String result = ownerService.importOwners(file.getInputStream());
            return ResultUtil.success(result);
        } catch (Exception e) {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "导入失败: " + e.getMessage());
        }
    }

    @RequestMapping(value = "/exportTemplate", method = RequestMethod.GET)
    @Operation(summary = "导出业主导入模板")
    public void exportTemplate(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        
        // 设置文件名
        String fileName = URLEncoder.encode("业主导入模板", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        // 创建示例数据
        List<OwnerData> templateData = new ArrayList<>();
        
        // 添加示例行
        OwnerData example = new OwnerData();
        example.setCellName("示例小区");
        example.setName("张三");
        example.setPhone("13800138000");
        example.setGender("男/女");
        example.setEmail("zhangsan@example.com");
        example.setIdCard("123456789012345678");
        example.setMoveInTime(new Date());
        example.setBuildingName("一栋");
        example.setUnitName("1单元");
        example.setNumber("101");
        example.setResidentType("业主/子女/亲戚/其他");
        example.setRemark("示例备注");
        templateData.add(example);
        
        // 写入Excel
        EasyExcel.write(response.getOutputStream(), OwnerData.class)
                .sheet("业主导入模板")
                .doWrite(templateData);
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @Operation(summary = "删除业主")
    public Result delete(@RequestParam Long ownerId) {
        if (ownerId == null) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), "业主ID不能为空");
        }
        
        boolean result = ownerService.deleteOwner(ownerId);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "删除业主失败");
        }
    }

    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @Operation(summary = "批量删除业主")
    public Result deleteBatch(@RequestBody List<Long> ownerIds) {
        if (ownerIds == null || ownerIds.isEmpty()) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), "业主ID列表不能为空");
        }
        
        boolean result = ownerService.deleteOwnerBatch(ownerIds);
        if (result) {
            return ResultUtil.success();
        } else {
            return ResultUtil.error(ErrorCode.OPERATION_ERROR.getCode(), "批量删除业主失败");
        }
    }

    @RequestMapping(value = "/searchByName", method = RequestMethod.GET)
    @Operation(summary = "根据业主名字模糊查询获取业主ID列表")
    public Result<List<OwnerSearchVo>> searchByName(@RequestParam String ownerName) {
        if (ownerName == null || ownerName.trim().isEmpty()) {
            return ResultUtil.error(ErrorCode.PARAMS_ERROR.getCode(), "业主名字不能为空");
        }
        
        List<OwnerSearchVo> ownerIds = ownerService.getOwnerIdsByName(ownerName.trim());
        return ResultUtil.success(ownerIds);
    }

}
